import React, { useState, useEffect } from 'react';
import {
  ConfigProvider,
  Form,
  Input,
  Row,
  Col,
  Select,
  Radio,
  Tabs,
  Button,
  Table,
  Checkbox,
  Descriptions,
} from 'antd';
import type { TableListItem, DataType } from './data';
import { Tab0, Tab1, Tab2, Tab3, Tab4 } from './value';
import {
  getDetail,
  saveDetailData,
  pendingAdd,
  pendingstatus,
  pendingtitle,
  readingAdd,
  readingUpdate,
} from './service';
import './index.less';

const { TextArea } = Input;
const { Group: CheckboxGroup } = Checkbox;
const { TabPane } = Tabs;

const Robbit: React.FC<TableListItem> = (props) => {
  const [tabKey, setTabKey] = useState('0');
  const [webRadio, setWebRadio] = useState(2);
  const [appRadio, setAppRadio] = useState(2);
  const [statusList, setStatusList] = useState([]);
  const [levelList, setLevelList] = useState([]);
  const [caseId, setCaseId] = useState('');

  const [form] = Form.useForm();
  const [form0] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();
  const [form4] = Form.useForm();

  useEffect(() => {
    const { id } = props.location.query;
    if (id) {
      setCaseId(id);
      getDetail(id).then((res) => {
        form.setFieldsValue(res.autoCase);
        res.autoCaseDetails.forEach((item: any) => {
          if (item.interfaceId === 0) {
            // form0.setFieldsValue(decodeURIComponent(JSON.parse(item.param)));
          } else if (item.interfaceId === 1) {
            // form1.setFieldsValue(decodeURIComponent(JSON.parse(item.param)));
          } else if (item.interfaceId === 2) {
            // form2.setFieldsValue(decodeURIComponent(JSON.parse(item.param)));
          } else if (item.interfaceId === 3) {
            // form3.setFieldsValue(decodeURIComponent(JSON.parse(item.param)));
          } else if (item.interfaceId === 4) {
            // form4.setFieldsValue(decodeURIComponent(JSON.parse(item.param)));
          }
        });
      });
    } else {
      form.resetFields();
      form0.resetFields();
      form1.resetFields();
      form2.resetFields();
      form3.resetFields();
      form4.resetFields();
    }
  }, [window.location.href]);

  const statusChange = (list: any) => {
    const List1 = list.filter((item) => statusList.indexOf(item) === -1);
    setStatusList(List1);
  };

  const levelChange = (list: any) => {
    const List2 = list.filter((item) => levelList.indexOf(item) === -1);
    setLevelList(List2);
  };

  const statusOpt = [
    { label: '待办', value: '0' },
    { label: '已办', value: '1' },
    { label: '删除', value: '2' },
  ];

  const levelOpt = [
    { label: '普通', value: '1' },
    { label: '重要', value: '2' },
    { label: '加急', value: '3' },
  ];

  const getRowKey = (row: any) => {
    // console.log('row', row);
    switch (row.key) {
      case 'pendingStatus':
        return (
          <Form.Item name="pendingStatus">
            <CheckboxGroup
              options={statusOpt}
              value={statusList}
              onChange={statusChange}
            />
          </Form.Item>
        );
      case 'pendingLevel':
        return (
          <Form.Item name="pendingLevel">
            <CheckboxGroup
              options={levelOpt}
              value={levelList}
              onChange={levelChange}
            />
          </Form.Item>
        );
      case 'pendingMobile':
        return (
          <Form.Item name="pendingMobile">
            <Radio.Group>
              <Radio value={'Y'}>是</Radio>
              <Radio value={'N'}>否</Radio>
            </Radio.Group>
          </Form.Item>
        );
      case 'pendingIsHandleMyself':
        return (
          <Form.Item name="pendingIsHandleMyself">
            <Radio.Group>
              <Radio value={'Y'}>是</Radio>
              <Radio value={'N'}>否</Radio>
            </Radio.Group>
          </Form.Item>
        );
      case 'pendingMobileProcess':
        return (
          <Form.Item name="pendingMobileProcess">
            <Radio.Group>
              <Radio value={'Y'}>是</Radio>
              <Radio value={'N'}>否</Radio>
            </Radio.Group>
          </Form.Item>
        );
      default:
        return (
          <Form.Item name={row.key}>
            <Input />
          </Form.Item>
        );
    }
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: '100px',
      render: (text, rocord, index) => index + 1,
    },
    {
      title: '字段名称(中文)',
      dataIndex: 'apichina',
    },
    {
      title: '字段名称(英文)',
      dataIndex: 'apieng',
    },
    {
      title: '字段说明及逻辑',
      dataIndex: 'inform',
    },
    {
      title: '字段值',
      dataIndex: 'status',
      width: '300px',
      render: (_, row) => {
        return getRowKey(row);
      },
    },
  ];

  const formInstances = [form0, form1, form2, form3, form4];

  const tabContent = [
    {
      key: '0',
      title: '新增待办接口',
      data: Tab0,
    },
    {
      key: '1',
      title: '更新待办状态或Url',
      data: Tab1,
    },
    {
      key: '2',
      title: '更新待办标题',
      data: Tab2,
    },
    {
      key: '3',
      title: '新增待阅',
      data: Tab3,
    },
    {
      key: '4',
      title: '更新待阅状态',
      data: Tab4,
    },
  ];

  const onChange = (key: string) => {
    setTabKey(key);
  };

  const saveData = async (params?: {
    autoCase: any;
    autoCaseDetails: { interfaceId: number; param: string }[];
  }) => {
    try {
      const autoCase = await form.validateFields();
      const tabs0 = form0.validateFields();
      const tabs1 = form1.validateFields();
      const tabs2 = form2.validateFields();
      const tabs3 = form3.validateFields();
      const tabs4 = form4.validateFields();
      const results = await Promise.all([tabs0, tabs1, tabs2, tabs3, tabs4]);
      if (caseId) {
        autoCase.caseId = caseId;
      }
      const params = {
        autoCase,
        autoCaseDetails: [
          {
            interfaceId: 0,
            param: encodeURIComponent(JSON.stringify(results[0])),
          },
          {
            interfaceId: 1,
            param: encodeURIComponent(JSON.stringify(results[1])),
          },
          {
            interfaceId: 2,
            param: encodeURIComponent(JSON.stringify(results[2])),
          },
          {
            interfaceId: 3,
            param: encodeURIComponent(JSON.stringify(results[3])),
          },
          {
            interfaceId: 4,
            param: encodeURIComponent(JSON.stringify(results[4])),
          },
        ],
      };
      saveDetailData(params).then((res) => {
        setCaseId(res.autoCase.caseId);
      });
    } catch (error) {
      console.log(error);
    }
  };

  const saveDo = async () => {};

  return (
    <ConfigProvider autoInsertSpaceInButton={false}>
      <div className="detail-wrapper">
        <Form layout="vertical" form={form}>
          {/* <div className="apply-info">
            <div className="apply-info-til">申请人信息</div>
            <div>
              <Descriptions>
                <Descriptions.Item label="申请人">张三</Descriptions.Item>
                <Descriptions.Item label="申请组织">
                  中国联通软件研究院
                </Descriptions.Item>
                <Descriptions.Item label="申请部门">
                  信息管理部
                </Descriptions.Item>
                <Descriptions.Item label="手机号">
                  131****1234
                </Descriptions.Item>
                <Descriptions.Item label="应用接入自动测试介绍流程规范介绍">
                  XXXX
                </Descriptions.Item>
              </Descriptions>
            </div>
          </div> */}
          <div className="base-form">
            <div className="base-form-til">基础信息</div>
            <Row>
              <Col span={8}>
                <Form.Item
                  label="测试用例名称"
                  name="caseName"
                  className="base-form-item"
                  // rules={[{ required: true }]}
                >
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="应用名称"
                  name="appName"
                  className="base-form-item"
                  // rules={[{ required: true }]}
                >
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="自动测试环境"
                  name="environmentId"
                  // rules={[{ required: true }]}
                >
                  <Select
                    // style={{ width: 120 }}
                    placeholder="请输入"
                    options={[
                      {
                        value: '0',
                        label: '测试环境',
                      },
                      {
                        value: '1',
                        label: '开发环境',
                      },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="应用是否接入智慧门户待办待阅"
                  name="workPortal"
                  className="base-form-item"
                  // rules={[{ required: true }]}
                >
                  <Radio.Group value={webRadio}>
                    <Radio value={1}>是</Radio>
                    <Radio value={2}>否</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="应用是否接入联通APP待办待阅"
                  name="workApp"
                  className="base-form-item"
                  // rules={[{ required: true }]}
                >
                  <Radio.Group value={appRadio}>
                    <Radio value={1}>是</Radio>
                    <Radio value={2}>否</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="应用链接"
                  name="appUrl"
                  // rules={[{ required: true }]}
                >
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item label="应用介绍" name="appExplain">
                  <TextArea rows={4} placeholder="请输入" maxLength={6} />
                </Form.Item>
              </Col>
            </Row>
          </div>
        </Form>
        <div className="post-form">
          <div className="post-form-til">待办待阅接口信息</div>
          <Tabs onChange={onChange}>
            {tabContent.map((source, index) => (
              <TabPane tab={`Tab ${source.title}`} key={source.key}>
                <Form form={formInstances[index]}>
                  {/* <Button
                    type="primary"
                    style={{ width: '100px', marginBottom: '16px' }}
                    onClick={saveDo}
                  >
                    保存并执行
                  </Button> */}
                  <Table
                    columns={columns}
                    dataSource={source.data}
                    pagination={false}
                  />
                </Form>
              </TabPane>
            ))}
          </Tabs>
          <Form.Item label="请求报文" style={{ margin: '16px 0' }}>
            <TextArea rows={4} maxLength={6} disabled={true} />
          </Form.Item>
          <Form.Item label="接口返回报文">
            <TextArea rows={4} maxLength={6} disabled={true} />
          </Form.Item>
        </div>
        <div className="foot-form">
          {/* <Button style={{ marginRight: '8px' }}>返回</Button> */}
          <Button type="primary" onClick={saveData}>
            确认
          </Button>
        </div>
      </div>
    </ConfigProvider>
  );
};

export default Robbit;
